const XLSX = require('xlsx')

function getExcelFileStream (data, columnWidths) {
  try {
    const worksheet = XLSX.utils.aoa_to_sheet(data)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
    if (columnWidths?.length) {
      worksheet['!cols'] = columnWidths
    }
    const stream = XLSX.write(workbook, {
      type: 'buffer',
      bookType: 'xlsx',
      cellStyles: true
    })
    return stream
  } catch (error) {
    throw new Error(error)
  }
}

module.exports = getExcelFileStream
